""" MembershipFunctions

This module contains implementation of Membership functions. 
Each function has a name (good, bad, tall, low...) and some points 
that defines the membership shape



2006 (C) Pollini Andrea

this file si released under LGPL license 2.0  ora above.
"""


__author__ = "Pollini Andrea  nelson1977@gmail.com"

"""
  __membership_function_registry is a dictionary of dictonary that
contains the info of each membership function
"""
__membership_function_registry = {}    
    
def register_membership_function(aType, aClass, nArgs):
    """register_membership_function
        
       This function registers a new membership function. You can use
        it to register your own membership functions.
    """
    memb_infos = {'obj_class': aClass, 'n_args': nArgs}
    __membership_function_registry[aType] = memb_infos



def make_membership_function(aType,name,**kwargs):
    """
    The Memebership function Factory.
    """
    memb_info = __membership_function_registry[aType]
    memb_func = MembershipFunction(name,**kwargs)
    memb_func.__class__ = memb_info['obj_class']
    return memb_func
 



class MembershipFunction(object):
    
    def __init__(self, name, **kwargs):
        self.name = name
        self.values = kwargs['values']
        self.min_value = min(self.values)
        self.max_value = max(self.values)
        

    
    
class TriangularMembershipFunction(MembershipFunction):
    
    def __init__(self, name, **kwargs):
        MembershipFunction.__init__(self, name,values=kwargs['values'])
        
        
    def __call__(self,aCrisp):
        if aCrisp >= self.max_value or aCrisp <= self.min_value: 
            return 0
        
        if aCrisp <= self.values[1]:
            return (aCrisp - self.values[0])/(self.values[1] - self.values[0])
        else:
            return (self.values[2] - aCrisp)/(self.values[2] - self.values[1])
        
class TrapezioidalMembershipFunction(MembershipFunction):     
    

    def __init__(self, name, **kwargs):
        MembershipFunction.__init__(self, name,values=kwargs['values'])
        
        
            
    def __call__(self,aCrisp):
        if aCrisp >= self.max_value or aCrisp <= self.min_value: 
            return 0.0
        
        if aCrisp >= self.values[1] and aCrisp <= self.values[2]:
            return 1.0    
        
        if aCrisp <= self.values[1]:
            return (aCrisp - self.values[0])/(self.values[1] - self.values[0])
        elif aCrisp >= self.values[2]:
            return (self.values[3] - aCrisp)/(self.values[3] - self.values[2])

register_membership_function("TRIANGULAR",TriangularMembershipFunction,3)
register_membership_function("TRAPEZIOIDAL",TrapezioidalMembershipFunction,4)


t = TriangularMembershipFunction("basso",values=[0,1.2,2.5])
t1 = make_membership_function("TRIANGULAR","prova",values=[0,1.2,2.5])
print t(1),t(2),t(3),t(4)
print t1(1),t1(2),t1(3),t1(4)